package com.robam.cloud.common.util.cmcc;

import java.security.MessageDigest;

/**
 * <p>
 * 文件名称: EncryptionUtil.java
 * </p>
 *
 * <p>
 * 文件功能: 加密工具类,
 * <ul>
 * <li>MD5</li>
 * </ul>
 * </p>
 * <p>
 * 版本: version 1.0
 * </p>
 */
public class EncryptionUtil {

    private static final String DEFAULT_ENCODING = "UTF-8";
    private static final char[] HEX_DIGITS = "0123456789ABCDEF".toCharArray();

    /**
     * Description： md5 加密
     * <p>
     * 参数为String
     * <p>
     *
     * @param data
     * @return String
     * @author name：lljqiu
     * <p>
     * = ===========================================
     * </p>
     * Modified No： Modified By： Modified Date： Modified Description:
     * <p>
     * = ===========================================
     * </p>
     **/
    public static String encryptMD5(String data) {
        return data == null ? null : hashEncrypt(data, "MD5");
    }

    private static String hashEncrypt(String data, String algorithm) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(data.getBytes(DEFAULT_ENCODING));
            return bytes2Hex(md.digest());
        } catch (Exception never) {
            throw new RuntimeException("MD5加密失败", never);
        }
    }

    /**
     * Description： byte ==>> String
     *
     * @param bytes
     * @return String
     * @author name：lljqiu
     **/
    private static String bytes2Hex(byte[] bytes) {
        int len = bytes.length;
        char[] str = new char[len * 2];
        for (int i = 0; i < len; i++) {
            byte b = bytes[i];
            str[i * 2] = HEX_DIGITS[b >>> 4 & 0xF];
            str[i * 2 + 1] = HEX_DIGITS[b & 0xF];
        }
        return new String(str);
    }

}
